package com.yonyoucloud.fi.pcm.track.billrule.unionRealWeight;

import com.yonyou.ucf.mdd.common.model.rule.RuleExecuteResult;
import com.yonyou.ucf.mdd.ext.bill.rule.base.AbstractCommonRule;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdd.ext.dao.meta.MetaDaoHelper;
import com.yonyou.ucf.mdd.ext.model.BillContext;
import com.yonyoucloud.fi.pcm.accParam.AccParam;
import com.yonyoucloud.fi.pcm.base.AccountInfo;
import com.yonyoucloud.fi.pcm.consts.ImportMessage;
import com.yonyoucloud.fi.pcm.consts.ResponseMessage;
import com.yonyoucloud.fi.pcm.dto.importDto.AccInfoDTO;
import com.yonyoucloud.fi.pcm.dto.importDto.ImportCheckDTO;
import com.yonyoucloud.fi.pcm.realco.RealCo;
import com.yonyoucloud.fi.pcm.rule.ProductType;
import com.yonyoucloud.fi.pcm.rule.UnionRealWeight;
import com.yonyoucloud.fi.pcm.util.PcmImportUtils;
import com.yonyoucloud.fi.pcm.util.PcmVoucherUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.imeta.core.lang.NumberUtils;
import org.imeta.orm.schema.QueryCondition;
import org.imeta.orm.schema.QueryConditionGroup;
import org.imeta.orm.schema.QuerySchema;
import org.imeta.spring.support.id.IdManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author lixilin
 * @Description: 导入规则
 * @date 2020/9/28
 */
public class UnionRealWeightImportRule extends AbstractCommonRule {
    private Logger logger = LoggerFactory.getLogger(UnionRealWeightImportRule.class);

    @Override
    public RuleExecuteResult execute(BillContext billContext, Map<String, Object> paramMap) throws Exception {
        RuleExecuteResult ruleResult = new RuleExecuteResult();
//        List<Map<String, Object>> factoryData = searchFactoryData();
//        List<Map<String, Object>> factoryData1 = searchFactoryData1();
        Map<String, Object> resultMaps = new HashMap<>();
        int listSize =0;
        if (MapUtils.isEmpty(paramMap)) {
            logger.debug("导入数据为空...");
            resultMaps.put("listSize", listSize);// Exel导入总条数
            resultMaps.put("successCount", 0);// 全部失败
            ruleResult.setMessage(ImportMessage.WITHOUT_IMPORT_DATA);
            ruleResult.setData(resultMaps);
            return ruleResult;
        }
        List<HashMap> importData = null;
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            if (entry.getValue() instanceof List) {
                importData = (List<HashMap>)entry.getValue();
            }
        }
        if (CollectionUtils.isEmpty(importData)) {
            logger.debug("导入数据为空...");
            resultMaps.put("listSize", listSize);// Exel导入总条数
            resultMaps.put("successCount", 0);// 全部失败
            ruleResult.setMessage(ImportMessage.WITHOUT_IMPORT_DATA);
            ruleResult.setData(resultMaps);
            return ruleResult;
        }
        listSize = importData.size();
        StopWatch stopwatch = new StopWatch();
        stopwatch.start();
        Set<String> factoryIdSet = new HashSet<>();

        List<Map<String, Object>> accInfoData = searchAccInfoData();
        if (CollectionUtils.isEmpty(accInfoData)) {
            logger.debug("成本核算期间数据为空...");
            resultMaps.put("listSize", listSize);// Exel导入总条数
            resultMaps.put("successCount", 0);// 全部失败
            ruleResult.setMessage(ResponseMessage.WITHOUT_ACCINFO_DATA);
            ruleResult.setData(resultMaps);
            return ruleResult;
        }
        AccInfoDTO accInfoDTO = PcmImportUtils.getBusiaccbookByAccInfo(accInfoData);
        Set<Long> accPurposesIdSet =accInfoDTO.getAccPurposesIdSet();
        Set<Long> controlScopeIdSet = accInfoDTO.getControlScopeIdSet();
        Set<String> accentityIdSet = accInfoDTO.getAccentityIdSet();
        Set<Long> busiaccbookIdSet = accInfoDTO.getBusiaccbookIdSet();
        Map<String, Long> accbookMap = accInfoDTO.getAccbookMap();
        StringBuilder sb = new StringBuilder();
        // 查询产品名称编码和自由项对应的ia_material_id
        Map<String, Long> iaMaterialId = PcmImportUtils.searchIaMaterialIdMap();
        if (MapUtils.isEmpty(iaMaterialId)) {
            logger.debug("物料规格数据为空...");
            resultMaps.put("listSize", listSize);// Exel导入总条数
            ruleResult.setMessage(ImportMessage.MAT_DATA_ISNULL);
            ruleResult.setData(resultMaps);
            return ruleResult;
        }

        // 主核算对象的ia_material_id和工厂id的映射
        Map<Long, String> maincoIaMaterialIdToFactoryId = searchMaincoIaMaterialIds();
        if (CollectionUtils.isEmpty(maincoIaMaterialIdToFactoryId)) {
            logger.debug("主核算对象物料规格数据为空...");
            resultMaps.put("listSize", listSize);// Exel导入总条数
            resultMaps.put("successCount", 0);// 全部失败
            ruleResult.setMessage(ImportMessage.REALCO_DATA_ISNULL);
            ruleResult.setData(resultMaps);
            return ruleResult;
        }
        Map<String, UnionRealWeight> dbUnionRealWeightMap = searchDbUnionRealWeightData(accPurposesIdSet, controlScopeIdSet, accentityIdSet, busiaccbookIdSet, factoryIdSet);
        stopwatch.stop();
        logger.debug("-----------------联产品权重导入--搜索数据库数据耗时: {}s-----------------", stopwatch.getTotalTimeSeconds());
        stopwatch.start();
        StringBuilder errorMsg = new StringBuilder();
        // 四要素都非空依次过滤,组装数据
        StringBuilder productKey = new StringBuilder();
        StringBuilder productFree = new StringBuilder();
        String subPcmProductPreFree = "subPcmProduct_freeval";
        String mainPcmProductPreFree = "mainPcmProduct_freeval";
        int size = new Double(importData.size() / 0.75 + 1).intValue();
        Map<String, UnionRealWeight> importUnionRealWeight = new HashMap<>(size);
        Set<Long> deleteIds = new HashSet<>();
        Long tenant = NumberUtils.L(AppContext.getCurrentUser().getTenant());
        Integer appLevel = PcmImportUtils.getAppLevel();
        for (HashMap data : importData) {
            int rowNum = NumberUtils.i(data.get("__rowNum"));
           /* Long accpurpose = null;
            Long controlScope = null;
            if (appLevel == 1) { //只有YB租户的校验核算目的和管控范围并拼错误提示信息
                ImportCheckDTO accPurposesCheckDto = PcmImportUtils.checkFourElementId(errorMsg, data, rowNum, ImportMessage.IMPORT_CHECK_ACCPURPOSES_KEY, ImportMessage.ACCPURPOSES);
                if (Objects.isNull(accPurposesCheckDto.getDbData())) {
                    errorMsg = accPurposesCheckDto.getErrorMsg();
                    continue;
                }
                accpurpose = NumberUtils.L(accPurposesCheckDto.getDbData());
                ImportCheckDTO controlScopeCheckDto = PcmImportUtils.checkFourElementId(errorMsg, data, rowNum, ImportMessage.IMPORT_CHECK_CONTROLSCOPE_KEY, ImportMessage.CONTROLSCOPE);
                if (Objects.isNull(controlScopeCheckDto.getDbData())) {
                    errorMsg = controlScopeCheckDto.getErrorMsg();
                    continue;
                }
                controlScope = NumberUtils.L(controlScopeCheckDto.getDbData());
            } else {
                accpurpose = NumberUtils.L(data.get(ImportMessage.IMPORT_CHECK_ACCPURPOSES_KEY));
                controlScope = NumberUtils.L(data.get(ImportMessage.IMPORT_CHECK_CONTROLSCOPE_KEY));
            }*/

            Long accpurpose = NumberUtils.L(data.get(ImportMessage.IMPORT_CHECK_ACCPURPOSES_KEY));
            Long controlScope = NumberUtils.L(data.get(ImportMessage.IMPORT_CHECK_CONTROLSCOPE_KEY));
            String accentity = null;
            if (appLevel != 3) {// 只有不是单组织的租户校验会计主体并拼错误提示信息
                ImportCheckDTO accentityCheckDto = PcmImportUtils.checkImportAccentityId(errorMsg, data, rowNum, ImportMessage.IMPORT_CHECK_ACCENTITY_KEY, ImportMessage.ACCENTITY);
                if (Objects.isNull(accentityCheckDto.getDbData())) {
                    errorMsg = accentityCheckDto.getErrorMsg();
                    continue;
                }
                accentity = accentityCheckDto.getDbData().toString();

                if (Objects.isNull(accpurpose) || Objects.isNull(controlScope)) {
                    PcmImportUtils.getCommonErrorMsg(errorMsg, rowNum);
                    errorMsg.append(ImportMessage.ACCENTITY);
                    errorMsg.append(": ");
                    errorMsg.append(data.get("accentity_name"));
                    errorMsg.append(ImportMessage.NOT_FOUND_ACCBOOK);
                    continue;
                }
            } else {
                accentity = data.get(ImportMessage.IMPORT_CHECK_ACCENTITY_KEY).toString();
            }

//            ImportCheckDTO factoryCheckDto = PcmImportUtils.checkFourElementId(errorMsg, data, rowNum, ImportMessage.IMPORT_CHECK_FACTORY_KEY, ImportMessage.FACTORY);
//            if (Objects.isNull(factoryCheckDto.getDbData())) {
//                errorMsg = factoryCheckDto.getErrorMsg();
//                continue;
//            }
            String factory = "";// 保存核算对象中的工厂id数据
            sb.setLength(0);
            sb.append(accpurpose);
            // 10-17 成本期初的accinfo中的管控范围为空
//            sb.append("_");
//            sb.append(controlScope);
            sb.append("_");
            sb.append(accentity);
            Long busibook = accbookMap.get(sb.toString());
            if (appLevel != 3 && Objects.isNull(busibook)) {
                PcmImportUtils.getCommonErrorMsg(errorMsg, rowNum);
                errorMsg.append(ImportMessage.ACCENTITY);
                errorMsg.append(": ");
                errorMsg.append(data.get("accentity_name"));
                errorMsg.append(ImportMessage.NOT_FOUND_ACCBOOK);
                continue;
            }

            AccParam accParam = new AccParam(accpurpose, controlScope, accentity, busibook, null, null, factory);

            if (Objects.isNull(data.get("mainPcmProduct_code"))) {
                PcmImportUtils.getCommonErrorMsg(errorMsg, rowNum);
                errorMsg.append(ImportMessage.MAIN_PRODUCT);
                errorMsg.append(ImportMessage.NAME_OR_CODE_ERROR);
                continue;
            }
            Long mainIaMaterialId = PcmImportUtils.getIaMaterialIdByNameCodeAndFree("mainPcmProduct_code", iaMaterialId,productKey, productFree, mainPcmProductPreFree, data);
            if (Objects.isNull(mainIaMaterialId) || !maincoIaMaterialIdToFactoryId.keySet().contains(mainIaMaterialId)) {
                PcmImportUtils.getCommonErrorMsg(errorMsg, rowNum);
                errorMsg.append(ImportMessage.MAIN_PRODUCT);
                errorMsg.append(ImportMessage.FREE_ERROR);
                continue;
            }
            /** 12-22 联产品权重工厂为必输 **/
            Object factory_id = data.get("factory");
            if (Objects.isNull(factory_id)) {
                PcmImportUtils.getCommonErrorMsg(errorMsg, rowNum);
                errorMsg.append(ImportMessage.FACTORY);
                errorMsg.append(ImportMessage.NAME_OR_CODE_ERROR);
                continue;
            }
            factory = String.valueOf(factory_id);
            accParam.setFactory(factory);

            if (Objects.isNull(data.get("subPcmProduct_code"))) {
                PcmImportUtils.getCommonErrorMsg(errorMsg, rowNum);
                errorMsg.append(ImportMessage.PRODUCT);
                errorMsg.append(ImportMessage.NAME_OR_CODE_ERROR);
                continue;
            }
            Long subIaMaterialId = PcmImportUtils.getIaMaterialIdByNameCodeAndFree("subPcmProduct_code", iaMaterialId,productKey, productFree, subPcmProductPreFree, data);
            if (Objects.isNull(subIaMaterialId)) {
                PcmImportUtils.getCommonErrorMsg(errorMsg, rowNum);
                errorMsg.append(ImportMessage.PRODUCT);
                errorMsg.append(ImportMessage.FREE_ERROR);
                continue;
            }
            ProductType productType = getProductType(data);
            if (Objects.isNull(productType)) {
                PcmImportUtils.getCommonErrorMsg(errorMsg, rowNum);
                errorMsg.append(ImportMessage.UNION_PRODUCT_TYPE_ERROR);
                continue;
            }
///            是否折算不可修改,且需要折算
///            Object convert = data.get("convert");
///            Boolean convertValue = PcmImportUtils.getImportBooleanValue(convert);

            Boolean convertValue = Boolean.TRUE;

            Object ratio = data.get("convertRatio");
            BigDecimal convertRatio;
            // 折算系数必须试大于零的正数(默认是一)
            if(Objects.isNull(ratio)){
                convertRatio = BigDecimal.ONE;
            } else {
                if (!PcmImportUtils.checkStrIsNum(ratio.toString(), true)) {
                    PcmImportUtils.getCommonErrorMsg(errorMsg, rowNum);
                    errorMsg.append(ImportMessage.CONVERT_RATIO_ERROR);
                    continue;
                }
                convertRatio = NumberUtils.bigD(ratio);
            }
            if (BigDecimal.ZERO.compareTo(convertRatio) == 0) {
                PcmImportUtils.getCommonErrorMsg(errorMsg, rowNum);
                errorMsg.append(ImportMessage.CONVERT_RATIO_ERROR);
                continue;
            }

            BigDecimal costweight = BigDecimal.ZERO;
            if(Objects.nonNull(data.get("costweight"))){
                if (!PcmImportUtils.checkStrIsNum(data.get("costweight").toString(), true)) {
                    PcmImportUtils.getCommonErrorMsg(errorMsg, rowNum);
                    errorMsg.append(ImportMessage.COST_WEIGHT_ERROR);
                    continue;
                }
                costweight =  NumberUtils.bigD(data.get("costweight"));
            }

            UnionRealWeight unionRealWeight = constructUnionWeightData(accParam, mainIaMaterialId, subIaMaterialId, productType, convertValue, convertRatio, costweight);
            unionRealWeight.put("__rowNum", rowNum);

            /**21-5-7 添加部门字段**/
            Object productionDept = data.get("productionDept");
            if (Objects.nonNull(productionDept)) {
                unionRealWeight.setProductionDept(productionDept.toString());
            }

            StringBuilder uniqueKey = getUniqueKey(productKey, unionRealWeight);
            UnionRealWeight dbData = dbUnionRealWeightMap.get(uniqueKey.toString());
            if (Objects.nonNull(dbData)) {
                /*** 9-27提示数据库已存在当前数据 跳过不处理**/
//                PcmImportUtils.getCommonErrorMsg(errorMsg, rowNum);
//                errorMsg.append(ImportMessage.DB_EXIST_CUR_DATA);
//                continue;
                /** 11-25 数据库存在的数据就更新 **/
                deleteIds.add(dbData.getId());
                unionRealWeight.setId(dbData.getId());
            }else {
                unionRealWeight.setId(IdManager.getInstance().nextId());
            }
            UnionRealWeight execlData = importUnionRealWeight.get(uniqueKey.toString());
            if (Objects.nonNull(execlData)) {
                Integer oldRowNum = NumberUtils.I(execlData.get("__rowNum"));
                // 覆盖原来的值
                execlData.put("__rowNum", rowNum);
                execlData.setConvert(convertValue);
                execlData.setConvertRatio(convertRatio);
                execlData.setCostweight(costweight);
                errorMsg = PcmImportUtils.getDataRepeatMsg(errorMsg, rowNum, oldRowNum);
                continue;
            }
            importUnionRealWeight.put(uniqueKey.toString(), unionRealWeight);
        }


        StringBuilder sqlSuffix = new StringBuilder();
        StringBuilder auditValueBuilder = new StringBuilder();
        for (UnionRealWeight value : importUnionRealWeight.values()) {
            sqlSuffix.append("(");
            sqlSuffix.append(value.getAccPurposes());
            sqlSuffix.append(",'");
            sqlSuffix.append(value.getAccentity());
            sqlSuffix.append("',");
            sqlSuffix.append(value.getBusiaccbook());
            sqlSuffix.append(",");
            sqlSuffix.append(value.getControlScope());
            sqlSuffix.append(",");

//            String factory = value.getFactory();
//            if (Objects.isNull(factory)) {
//                sqlSuffix.append(factory);
//            }else {
//                sqlSuffix.append("'");
//                sqlSuffix.append(factory);
//                sqlSuffix.append("'");
//            }
            /** 12-22 联产品权重工厂为必输 **/
            sqlSuffix.append("'");
            sqlSuffix.append(value.getFactory());
            sqlSuffix.append("'");
            sqlSuffix.append(",");

          // 21-6-7部门为空 给默认值 ""
           String productionDept = value.getProductionDept();
           if (Objects.isNull(productionDept)) {
               sqlSuffix.append("''");
           } else {
               sqlSuffix.append("'");
               sqlSuffix.append(productionDept);
               sqlSuffix.append("'");
           }

            sqlSuffix.append(",");

            sqlSuffix.append(value.getMainPcmProduct());
            sqlSuffix.append(",");
            sqlSuffix.append(value.getSubPcmProduct());
            sqlSuffix.append(",");
            sqlSuffix.append(value.getProductType().getValue());
            sqlSuffix.append(",");
            sqlSuffix.append(value.getConvert());
            sqlSuffix.append(",");
            sqlSuffix.append(value.getConvertRatio());
            sqlSuffix.append(",");
            sqlSuffix.append(value.getCostweight());
            sqlSuffix.append(",");
            sqlSuffix.append(tenant);
            sqlSuffix.append(",");
            sqlSuffix.append(0);
            sqlSuffix.append(",");
            Object id = value.getId();
            sqlSuffix.append(id);
            sqlSuffix.append(",'");
            sqlSuffix.append(PcmVoucherUtils.getUnionRealWeightAuditValue(auditValueBuilder,value));
            sqlSuffix.append("'),");
        }

        if (StringUtils.isNotBlank(sqlSuffix.toString().trim())) {
            String insertSql = "insert into pcm_union_weight(accpurposes , accentity  , busiaccbook , controlscope ,factory_id,production_department_id," +
                    "main_pcm_product , sub_pcm_product, product_type , if_convert , convert_ratio ,cost_weight ,tenant_id,stopstatus,id,audit_value) value ";
            insertSql = insertSql + sqlSuffix.substring(0, sqlSuffix.length() - 1);
            resultMaps.put("insertSql", insertSql);
            String delMainSql = PcmImportUtils.getDeleteSqlByTableNameAndIds("pcm_union_weight", deleteIds);
            resultMaps.put("deleteSql", delMainSql);
        }
        resultMaps.put("listSize", listSize);// Exel导入总条数
        List msg = Collections.emptyList();
        if (StringUtils.isNotBlank(errorMsg.toString().trim())) {
            ruleResult.setMessage(errorMsg.toString());
        }
        resultMaps.put("failMessage", msg);// 失败提示信息
        ruleResult.setData(resultMaps);
        stopwatch.stop();
        logger.debug("-----------------联产品权重导入--数据校验拼装总耗时:{}s-----------------", stopwatch.getTotalTimeSeconds());
        return ruleResult;
    }

    private UnionRealWeight constructUnionWeightData(AccParam accParam, Long mainIaMaterialId, Long subIaMaterialId,
                                                    ProductType productType, Boolean convertValue, BigDecimal convertRatio, BigDecimal costweight) {
        UnionRealWeight unionRealWeight = new UnionRealWeight();
        unionRealWeight.setAccPurposes(accParam.getAccPurposes());
        unionRealWeight.setControlScope(accParam.getControlScope());
        unionRealWeight.setAccentity(accParam.getAccentity());
        unionRealWeight.setBusiaccbook(accParam.getBusiaccbook());
        unionRealWeight.setFactory(accParam.getFactory());
        unionRealWeight.setMainPcmProduct(mainIaMaterialId);
        unionRealWeight.setSubPcmProduct(subIaMaterialId);
        unionRealWeight.setProductType(productType);
        unionRealWeight.setConvert(convertValue);
        unionRealWeight.setConvertRatio(convertRatio);
        unionRealWeight.setCostweight(costweight);
        return unionRealWeight;
    }

    /**
     * 查询租户对应的当前期间的核算结果数据,用来确定四要素和期间数据
     *
     * @return
     * @throws Exception
     */
    private List<Map<String, Object>> searchAccInfoData() throws Exception {
        QueryConditionGroup queryConditionGroup = new QueryConditionGroup();
        QuerySchema schema = QuerySchema.create().addSelect("accPurposes,accentity,busiaccbook,controlScope").addCondition(queryConditionGroup);
        return MetaDaoHelper.query(AccountInfo.ENTITY_NAME, schema);
    }

    /**
     * 查询启用状态的主核算对象的物料规格id集合
     *
     * @return
     * @throws Exception
     */
    public static Map<Long,String> searchMaincoIaMaterialIds() throws Exception {
        QueryConditionGroup queryConditionGroup = QueryConditionGroup.and(
                QueryCondition.name("productType").eq(ProductType.MainProduct.getValue())
                ,QueryCondition.name("stopstatus").eq(Boolean.FALSE));
        QuerySchema schema = QuerySchema.create().addSelect("iaMaterialId,factory").addCondition(queryConditionGroup);
        List<Map<String, Object>> data = MetaDaoHelper.query(RealCo.ENTITY_NAME, schema);
        if (CollectionUtils.isEmpty(data)) {
            return Collections.emptyMap();
        }
        int size = new Double(data.size() / 0.75 + 1).intValue();
        Map<Long,String> MainIaMaterialIdToFactoryId = new HashMap<>(size);
        for (Map<String, Object> map : data) {
            if (Objects.nonNull(map.get("factory"))) {
                MainIaMaterialIdToFactoryId.put(NumberUtils.L(map.get("iaMaterialId")),map.get("factory").toString());
            }
        }
        return MainIaMaterialIdToFactoryId;
    }


    /**
     *  获取产出类型只要主产品和联产品
     * @param data
     * @return
     */
    private ProductType getProductType(HashMap data) {
        if (Objects.isNull(data.get("productType"))) {
            return null;
        }
        String type = data.get("productType").toString();
        if (ProductType.MainProduct.getName().equalsIgnoreCase(type) ||
                ProductType.MainProduct.toString().equalsIgnoreCase(type) ||
                String.valueOf(ProductType.MainProduct.getValue()).equalsIgnoreCase(type)
        ){
            return ProductType.MainProduct;
        }
        if (ProductType.Co_Product.getName().equalsIgnoreCase(type) ||
                ProductType.Co_Product.toString().equalsIgnoreCase(type) ||
                String.valueOf(ProductType.Co_Product.getValue()).equalsIgnoreCase(type)) {
            return ProductType.Co_Product;
        }
//        if (ProductType.By_Product.getName().equalsIgnoreCase(type)) {
//            return ProductType.By_Product;
//        }
//        if (ProductType.De_Product.getName().equalsIgnoreCase(type)) {
//            return ProductType.De_Product;
//        }
        return null;
    }

    /**
     * 查询租户对应的当前期间的核算结果数据,用来确定四要素和期间数据
     *
     * @return
     * @throws Exception
     */
    private List<Map<String, Object>> searchFactoryData() throws Exception {
        QueryConditionGroup queryConditionGroup = new QueryConditionGroup();
        QuerySchema schema = QuerySchema.create().addSelect("*").addCondition(queryConditionGroup);
        // 工厂实体 :org.func.Factory 这个是空指针异常
        return MetaDaoHelper.query("org.func.Factory", schema,"ucf-org-center");
    }
    private List<Map<String, Object>> searchFactoryData1() throws Exception {
        QueryConditionGroup queryConditionGroup = QueryConditionGroup.and(
                QueryCondition.name("orgtype").eq(2)
                // 启用
                ,QueryCondition.name("enable").eq(1)
                // 逻辑删除标识
                ,QueryCondition.name("dr").eq(0));
        QuerySchema schema = QuerySchema.create().addSelect("*").addCondition(queryConditionGroup);//org.func.FinanceOrg
        // org.func.FinanceOrg 这个表中的id既是会计主体id也是工厂id
        return MetaDaoHelper.query("org.func.FinanceOrg", schema,"ucf-org-center");//拿获取到的工厂的id去查询会计主体org.func.FinanceOrg
    }

    private Map<String, UnionRealWeight> searchDbUnionRealWeightData(Set<Long> accPurposesIdSet, Set<Long> controlScopeIdSet, Set<String> accentityIdSet, Set<Long> busiaccbookIdSet,
                                                                      Set<String> factoryIdSet) throws Exception {
        QueryConditionGroup queryConditionGroup = QueryConditionGroup.and(
                QueryCondition.name("accPurposes").in(accPurposesIdSet)
//                , QueryCondition.name("controlScope").in(controlScopeIdSet)
                , QueryCondition.name("accentity").in(accentityIdSet)
                , QueryCondition.name("busiaccbook").in(busiaccbookIdSet)
//                , QueryCondition.name("factory").in(factoryIdSet)
        );
        QuerySchema schema = QuerySchema.create().addSelect(
                "id,accPurposes,controlScope,accentity,busiaccbook,factory,productionDept,mainPcmProduct,subPcmProduct,productType"
        ).addCondition(queryConditionGroup);
        List<Map<String, Object>> dataList = MetaDaoHelper.query(UnionRealWeight.ENTITY_NAME, schema);
        if (CollectionUtils.isEmpty(dataList)) {
            return Collections.emptyMap();
        }
        StringBuilder sb = new StringBuilder();
        int size = new Double(dataList.size() /0.75 +1).intValue();
        Map<String, UnionRealWeight> rstMap = new HashMap<>(size);
        for (Map<String, Object> map : dataList) {
            UnionRealWeight unionRealWeight = new UnionRealWeight();
            unionRealWeight.init(map);
            sb = getUniqueKey(sb, unionRealWeight);
            rstMap.put(sb.toString(), unionRealWeight);
        }
        return rstMap;
    }

    private StringBuilder getUniqueKey(StringBuilder sb,  UnionRealWeight unionRealWeight) {
        sb.setLength(0);
        sb.append(unionRealWeight.getAccPurposes());
        sb.append("_");
        sb.append(unionRealWeight.getControlScope());
        sb.append("_");
        sb.append(unionRealWeight.getAccentity());
        sb.append("_");
        sb.append(unionRealWeight.getBusiaccbook());
        sb.append("_");
        sb.append(unionRealWeight.getFactory());
        sb.append("_");
        sb.append(unionRealWeight.getProductionDept());
        sb.append("_");
        sb.append(unionRealWeight.getMainPcmProduct());
        sb.append("_");
        sb.append(unionRealWeight.getSubPcmProduct());
//        sb.append("_");
//        sb.append(unionRealWeight.getProductType().getValue());
        return sb;
    }
}
